//
//  ARTNetworkEngine.m
//  ChartsDemo
//
//  Created by yunda on 2021/10/14.
//

#import "ARTNetworkEngine.h"

@interface ARTNetworkEngine()

// afn网络请求管理器
@property (strong, nonatomic)  AFHTTPSessionManager *sessionManager;
// json请求类型
@property (strong, nonatomic)  AFJSONRequestSerializer *jsonRequestSerializer;

@end

@implementation ARTNetworkEngine

/// 单利
static ARTNetworkEngine *manager;
+ (ARTNetworkEngine *)defaultManager{
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        manager = [[ARTNetworkEngine alloc] init];
    });
    return manager;
}

+ (void)load{
    [super load];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

- (void)requestWithDataModel:(ARTRequestModel * _Nonnull)dataModel progressCallback:(RequestProgressCallback _Nullable)progressBlock successdCallback:(RequestSuccessdCallback _Nullable)succeedBlock failedCallback:(RequestFailedCallback _Nullable)failedBlock{
    
    // 缓存策略
    NSString *requestTypeString = @"";
    if (dataModel.requestType == ARTRequestTypeGet) {
        // GET
        requestTypeString = @"GET";
    }else if (dataModel.requestType == ARTRequestTypePost){
        // POST
        requestTypeString = @"POST";
    }
    NSError *serializationError = nil;
    NSMutableURLRequest *request = [manager.sessionManager.requestSerializer requestWithMethod:requestTypeString URLString:dataModel.URLString parameters:dataModel.parameter error:&serializationError];
    __block NSURLSessionDataTask *sessionTask = [manager.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
        if (progressBlock) {
            dispatch_async(dispatch_get_main_queue(), ^{
                CGFloat values = downloadProgress.fractionCompleted;
                progressBlock(values);
            });
        }
    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            NSSLog(@"####REQUEST ERROR\n%@,\n错误信息=%@",[dataModel description],error);
            if (failedBlock) {
                failedBlock(error);
            }
        }else{
            ARTResponseModel *model = [ARTResponseModel mj_objectWithKeyValues:responseObject];
            if (!model) {
                model = [[ARTResponseModel alloc]init];
            }
            if (succeedBlock) {
                succeedBlock(model);
            }
            // 网络请求数据
            id expandData = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:NULL];
            NSSLog(@"####REQUEST SUCCESS\n%@,\n返回值expandData=%@",[dataModel description],expandData);
        }
    }];
    [sessionTask resume];
}

// 配置公共参数
- (void)configureCommonHeader{
    NSString *app_src = @"iOS";
    NSString *app_src_type = [NSString stringWithFormat:@"%@|%@",[QMUIHelper deviceName],[[UIDevice currentDevice] systemVersion]];
    NSString *app_id = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString *req_time = [[NSDate date] j_stringWithFormat:@"yyyyMMddHHmmss"];
    NSString *token = @"";
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *sign = @"";
    [_sessionManager.requestSerializer setValue:SAFE_STRING(app_src) forHTTPHeaderField:@"appsrc"];
    [_sessionManager.requestSerializer setValue:SAFE_STRING(app_src_type) forHTTPHeaderField:@"appsrctype"];
    [_sessionManager.requestSerializer setValue:SAFE_STRING(app_id) forHTTPHeaderField:@"app_id"];
    [_sessionManager.requestSerializer setValue:SAFE_STRING(req_time) forHTTPHeaderField:@"req_time"];
    [_sessionManager.requestSerializer setValue:SAFE_STRING(token) forHTTPHeaderField:@"token"];
    [_sessionManager.requestSerializer setValue:SAFE_STRING(version) forHTTPHeaderField:@"version"];
    [_sessionManager.requestSerializer setValue:SAFE_STRING(sign) forHTTPHeaderField:@"sign"];
    
    NSString *language = [NSUserDefaults jk_stringForKey:SET_LANGUAGE];
    if ([language isEqualToString:@"0"]) {
        language = @"zh";
    }else if ([language isEqualToString:@"1"]){
        language = @"en";
    }else if ([language isEqualToString:@"2"]){
        language = @"fr";
    }else{
        language = @"en";
    }
    NSLog(@"current launage=%@",language);
    [_sessionManager.requestSerializer setValue:SAFE_STRING(language) forHTTPHeaderField:@"language"];
}

- (AFHTTPSessionManager *)sessionManager{
    if (!_sessionManager) {
        _sessionManager = [AFHTTPSessionManager manager];
        _sessionManager.requestSerializer = manager.jsonRequestSerializer;
        AFHTTPResponseSerializer *httpResponseSerializer = [AFHTTPResponseSerializer serializer];
        //        httpResponseSerializer.removesKeysWithNullValues = YES;
        httpResponseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*",@"encoding=UTF-8", nil];
        _sessionManager.responseSerializer = httpResponseSerializer;
        // 处理AFNetworking与信号量使用时导致的死锁
        // 最大线程4
        //       _sessionManager.operationQueue.maxConcurrentOperationCount = 4;
        [self configureCommonHeader];
    }
    return _sessionManager;
}

- (AFJSONRequestSerializer *)jsonRequestSerializer{
    if (!_jsonRequestSerializer) {
        _jsonRequestSerializer = [AFJSONRequestSerializer serializer];
        [_jsonRequestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    }
    return _jsonRequestSerializer;
}

@end
